package com.csyf.manager.service.impl;

import com.csyf.manager.common.CommonConst;
import com.csyf.manager.dao.SysAgentChannelDao;
import com.csyf.manager.dao.SysMerchDao;
import com.csyf.manager.dao.SysTradeTypeDao;
import com.csyf.manager.entity.SysMerchant;
import com.csyf.manager.entity.SysTradeType;
import com.csyf.manager.entity.SysUser;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.exception.Exception;
import com.csyf.manager.service.SysMerchBiz;
import com.csyf.manager.service.SysUserService;
import com.csyf.manager.utils.page.JqGridVo;
import com.csyf.manager.utils.page.PageUtils;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author Enzo
 */
@Slf4j
@Service
@Transactional
public class SysMerchBizImpl implements SysMerchBiz {

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private SysMerchDao sysAgentdao;

    @Autowired
    private SysTradeTypeDao sysTradeTypeDao;

    @Autowired
    private SysAgentChannelDao sysAgentChannelDao;

    @Override
    public SysMerchant agentLogin(String accountName, String pwd) throws Exception {

        SysMerchant record = new SysMerchant();
        record.setMerchAccount(accountName);
        SysMerchant selectOne = sysAgentdao.selectOne(record);
        if (null == selectOne) {
            throw new Exception("账号错误");
        }
        if (!pwd.equals(selectOne.getMerchPwd())) {
            throw new Exception("密码错误");
        }
        return selectOne;
    }

    @Override
    public SysMerchant queryAgentByPhone(String phone) {
        SysMerchant record = new SysMerchant();
        record.setMerchPhone(phone);
        SysMerchant selectOne = sysAgentdao.selectOne(record);
        return selectOne;
    }

    @Override
    public SysMerchant queryAgentByMerchantNo(String merNo) {
        SysMerchant record = new SysMerchant();
        record.setMerchMerchantNo(merNo);
        SysMerchant selectOne = sysAgentdao.selectOne(record);
        return selectOne;
    }

    @Override
    public void modifyPwd(Long agentId, String oldPwd, String newPwd) throws Exception {
        SysMerchant selectOne = sysAgentdao.selectByPrimaryKey(agentId);

        if (null == selectOne) {
            throw new Exception("代理商不存在");
        }

        if (!oldPwd.equals(selectOne.getMerchPwd())) {
            throw new Exception("原始密码不正确");
        }
        log.info("修改代理商【{}】密码[{}]", selectOne.getMerchPhone(), newPwd);
        selectOne.setMerchPwd(newPwd);
        sysAgentdao.updateByPrimaryKeySelective(selectOne);
    }

    @Override
    public void stopAgent(Long agentId) {
        SysMerchant sysAgent = new SysMerchant();
        sysAgent.setId(agentId);
        sysAgent.setMerchStatus(0);
        sysAgentdao.updateByPrimaryKeySelective(sysAgent);

        log.info("将代理商【{}】禁用", agentId);
    }

    @Override
    public void startAgent(Long agentId) {
        SysMerchant sysAgent = new SysMerchant();
        sysAgent.setId(agentId);
        sysAgent.setMerchStatus(1);
        sysAgentdao.updateByPrimaryKeySelective(sysAgent);
        log.info("将代理商【{}】启用", agentId);
    }


    @Override
    public SysTradeType queryTradeType(String mch_id, String service) {

        SysTradeType sysTradeType = new SysTradeType();
        sysTradeType.setMch_id(mch_id);
        sysTradeType.setTradeType(service);
        sysTradeType.setStatus(1);
        return sysTradeTypeDao.selectOne(sysTradeType);
    }

    @Override
    public List<SysMerchant> queryAll() {
        return sysAgentdao.selectAll();
    }

    @Override
    public JqGridVo querydata(SysMerchant vo, Integer pageIndex, Integer pageSize) {

        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("id desc");

        Example example = new Example(SysMerchant.class);
        Example.Criteria criteria = example.createCriteria();
        PageUtils.andLikeTo(criteria, "merchName", "%" + vo.getMerchName() + "%");
        PageUtils.andEqualTo(criteria, "merchPhone", vo.getMerchPhone());
        PageUtils.andEqualTo(criteria, "merchMerchantNo", vo.getMerchMerchantNo());

        List<SysMerchant> select = sysAgentdao.selectByExample(example);
        return PageUtils.pasrJqGrid(select);
    }


    @Override
    public void saveAgent(SysMerchant vo) throws ApiValidateException {

        SysMerchant sysAgent = new SysMerchant();
        sysAgent.setMerchPhone(vo.getMerchPhone());
        int i = sysAgentdao.selectCount(sysAgent);
        if (i > 0) {
            throw new ApiValidateException("手机号重复");
        }
        sysAgent = new SysMerchant();
        sysAgent.setMerchAccount(vo.getMerchAccount());
        i = sysAgentdao.selectCount(sysAgent);
        if (i > 0) {
            throw new ApiValidateException("账号重复");
        }
        sysAgentdao.insertSelective(vo);


        //添加商户用户
        SysUser user = new SysUser();
        user.setUserName(vo.getMerchAccount());
        user.setPassword(vo.getMerchPwd());
        user.setCreateTime(new Date());
        user.setEmail(vo.getMerchMail());
        user.setMobile(vo.getMerchPhone());
        user.setStatus(CommonConst.STATUS_VALID.toString());
        user.setUserType(CommonConst.MERCH_USER);
        user.setDescription("商户用户");
        sysUserService.addUserAndGetId(user);

        //分配商户角色
        sysUserService.addAssignRole(user.getUserId(), Arrays.asList("3"));


        int i1 = new Random().nextInt(10);

        vo.setUserId(Long.valueOf(user.getUserId()));
        vo.setMerchStatus(1);
        String mer = "930000000";
        vo.setMerchMerchantNo(mer + (vo.getId() * 10 + i1));
        vo.setMerchSignkey(DigestUtils.md5Hex(vo.getMerchMerchantNo() + RandomStringUtils.random(4, "abcdefgABCDEFG123456789")));
        sysAgentdao.updateByPrimaryKey(vo);
    }

    /**
     * 根据Id查询代理商
     * @param agentId
     * @return
     */
    @Override
    public SysMerchant queryAgentById(Long agentId) {
        return sysAgentdao.selectByPrimaryKey(agentId);
    }

    /**
     * 根据Id删除代理商
     * @param agentId
     * @return
     */
    @Override
    public int deleteById(Long agentId) {
        return sysAgentdao.deleteByPrimaryKey(agentId);
    }

    /**
     * 根据代理商id更新代理商信息
     * @param agentForm
     * @return
     */
    @Override
    public int updateByAgentId(SysMerchant agentForm) {
        return sysAgentdao.updateByAgentId(agentForm);
    }

    /**
     * 根据商户id集合批量更新商户状态
     * @param merchIds
     * @param status
     * @return
     */
    @Override
    public int updateStatusBatch(List<String> merchIds, Integer status) {
        Map<String,Object> params = new HashMap<>(2);
        params.put("merchIds", merchIds);
        params.put("merchStatus", status);
        return sysAgentdao.updateStatusBatch(params);
    }

    /**
     * 根据用户id查询代理商Id
     * @param userId
     * @return
     */
    @Override
    public SysMerchant queryAgentByUserId(Long userId) {
        SysMerchant record = new SysMerchant();
        record.setUserId(userId);
        SysMerchant selectOne = sysAgentdao.selectOne(record);
        return selectOne;
    }

    /**
     * 根据代理商ID查询商户
     * @param agentId
     * @return
     */
    @Override
    public Set<Integer> findMerchByAgentId(Long agentId) {
        return sysAgentdao.findMerchByAgentId(agentId);
    }


}
